<template>
  <div id="app">
    <el-dialog :visible.sync="dialogVisible" title="发送消息" center top="10px">
      <div>
        <el-radio v-model="radio" label="1">群发</el-radio>
        <el-radio v-model="radio" label="2">定向发送</el-radio>
        <el-select size="small" clearable filterable v-model="user" v-if="radio=='2'" multiple
                   placeholder="请选择人员" style="width: 500px">
          <el-option v-for="item in userList" :key="item.userId" :label="item.nickName"
                     :value="item.userId">
          </el-option>
        </el-select>
      </div>
      <div style="border: 1px solid #ccc;margin-top: 20px" v-if="radio">
        <p style="display: flex;align-items: center;padding: 10px 20px;justify-content: space-around"><span
            style="display: block;width: 80px">正标题：</span>
          <el-input v-model="title" size="small" style="width: 100%"></el-input>
        </p>
        <p style="display: flex;align-items: center;padding: 10px 20px;justify-content: space-around"><span
            style="display: block;width: 80px">副标题：</span>
          <el-input v-model="subTitle" size="small" style="width: 100%"></el-input>
        </p>
        <div style="display: flex;align-items: center;padding: 10px 20px;justify-content: flex-start"><span
            style="display: block;width: 80px">缩略图：</span>
          <el-upload
              multiple
              class="uploader-wrap"
              :headers="headers"
              :action="`${this.$apiHost}/img/fileImgUrl`"
              :on-success="onSuccess"
              :show-file-list="false"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <template #tip>
              <div class="img-wrap">
                <el-image
                    v-for="(item, index) in productImgs"
                    :key="index + item"
                    :src="'https://'+item"
                    :preview-src-list="['https://'+item]"
                    class="img-item"
                    fit="cover"
                >
                </el-image>
              </div>
            </template>
          </el-upload>
        </div>

        <Toolbar
            style="border-bottom: 1px solid #ccc"
            :editor="editor"
            :defaultConfig="toolbarConfig"
            :mode="mode"
        />
        <Editor
            style="height: 500px; overflow-y: hidden;"
            v-model="html"
            :defaultConfig="editorConfig"
            :mode="mode"
            @onCreated="onCreated"
        />
      </div>
      <span slot="footer">
        <el-button style="color: #FFFFFF" @click="sendMessage" v-if="radio">发 送</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {Editor, Toolbar} from '@wangeditor/editor-for-vue'
import axios from "axios";

export default {
  name: "sendDialog",
  components: {Editor, Toolbar},
  data() {
    return {
      dialogVisible: false,
      radio: "",
      title: "发布公告",
      subTitle: "",
      user: [],
      userList: [],
      productImgs: [],
      editor: null,
      html: '<p>hello</p>',
      toolbarConfig: {},
      mode: 'default',
      editorConfig: {
        placeholder: '请输入内容...',
        MENU_CONF: {
          uploadImage: {
            maxFileSize: 1 * 1024 * 1024, // 1M
            base64LimitSize: 5 * 1024, // 5kb
            allowedFileTypes: ["image/*"],
            async customUpload(file, insertFn) {
              const formData = new FormData()
              formData.append('file', file);
              const res = await axios.post(`${this.$apiHost}/img/fileImgUrl`, formData, {
                headers: {
                  'Content-Type': 'multipart/form-data',
                  'token': window.$quinn.getStorage("tokenv3")
                }
              })
              if (res) {
                insertFn('https://' + res.data.result[0], "")
              } else {
                this.$message.error('图片上传失败，请重新上传!');
              }
            },
          }
        }
      },
    }
  },
  computed: {
    headers() {
      const token = window.$quinn.getStorage("tokenv3")
      return {
        token,
      };
    }
  },
  methods: {
    handleOpen(val) {
      // console.log(val)
      this.dialogVisible = true
      this.userList = val
    },
    onCreated(editor) {
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
    },
    onSuccess(res) {
      const {productImgs = []} = this;
      if (res.code == 200 && res.result) {
        productImgs.push(res.result[0]);
        this.productImgs = productImgs;
      }
    },
    sendMessage() {
      if (this.radio == 1) {
        this.user = []
      }
      const data = {
        receiveUserIds: this.user,
        content: this.html,
        title: this.title,
        subTitle: this.subTitle,
        coverPicture: this.productImgs.toString()
      }
      this.$api.messageAddMessage(data).then(res => {
        if (res == 1) {
          this.$message.success("发送成功！")
          this.dialogVisible = false
        }
      })
    }
  },

  mounted() {
    // 模拟 ajax 请求，异步渲染编辑器
    // setTimeout(() => {
    //   this.html = ''
    // }, 1500)
  }
  ,
  beforeDestroy() {
    const editor = this.editor
    if (editor == null) return
    editor.destroy() // 组件销毁时，及时销毁编辑器
  }
}
</script>
<style src="@wangeditor/editor/dist/css/style.css"></style>
<style scoped>
</style>